package top.codef.secure.handlers;

import java.io.IOException;

import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import com.fasterxml.jackson.databind.ObjectMapper;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import top.codef.secure.pojomodel.SecureResponseEnum;

public class CerberusExceptionTranslateHandler implements AuthenticationEntryPoint {

	private final ObjectMapper objectMapper;

	public CerberusExceptionTranslateHandler(ObjectMapper objectMapper) {
		this.objectMapper = objectMapper;
	}

	@SuppressWarnings("deprecation")
	@Override
	public void commence(HttpServletRequest request, HttpServletResponse response,
			AuthenticationException authException) throws IOException, ServletException {
		response.setStatus(HttpStatus.UNAUTHORIZED.value());
		response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
		response.getWriter().write(objectMapper.writeValueAsString(
				SecureResponseEnum.AUTH_FAIL.createSecureModel("用户验证异常：" + authException.getMessage())));
		response.flushBuffer();
	}

}
